package com.yenlien.traceyun.business.service;


import com.yenlien.traceyun.business.dao.CheckDao;
import com.yenlien.traceyun.business.entity.Check;
import com.yenlien.traceyun.business.service.rest.usercenter.FileRestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import java.util.*;

/**
 * Created by LiuSha on 2020/6/11.
 */
@Service
public class CheckService {
    @Autowired
    private CheckDao checkDao;
    @Autowired
    private FileRestService fileRestService;

    public Page<Check> findByList(final Check check) {
        Pageable pageable = PageRequest.of(check.getPage(), check.getPageSize(), Sort.Direction.DESC, "createtime");
        return checkDao.findAll(new Specification<Check>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Check> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> companyId = root.get("companyId");
                Path<String> checkName = root.get("checkName");
                //构造查询条件
                List<Predicate> list = new ArrayList<>();
                if (!StringUtils.isEmpty(check.getCompanyId())) {
                    list.add(cb.equal(companyId, check.getCompanyId()));
                }
                if (!StringUtils.isEmpty(check.getCheckName())) {
                    list.add(cb.like(checkName, "%" + check.getCheckName() + "%"));
                }
                Predicate[] predicate = new Predicate[list.size()];
                return cb.and(list.toArray(predicate));
            }
        }, pageable);
    }

    public void save(Check check, List<MultipartFile> files) throws Exception {
        fileRestService.upload(null, check, files);
        checkDao.save(check);
    }

    @Transactional
    public void update(Check check, List<MultipartFile> files) throws Exception {
        fileRestService.upload(checkDao.findById(check.getId()), check, files);
        checkDao.save(check);
    }


    public Check findById(String id) {
        return checkDao.findById(id);
    }

    public void delete(String id) {
        checkDao.deleteById(id);
    }

    public List<Check> findAll(String companyId) {
        if (!StringUtils.isEmpty(companyId)) {
            return checkDao.findByCompanyId(companyId);
        }
        return checkDao.findAll();
    }
}
